package server

import (
	"fmt"
	"net"
	"bufio"
	"strings"
	"github.com/sirupsen/logrus"
)


func Run() {

	logrus.SetFormatter(&logrus.TextFormatter {
		ForceColors: true,
		FullTimestamp: true,
	})

	logrus.Info("listen starting..")
	address := "0.0.0.0:6657"
	listener, err := net.Listen("tcp", address)
	defer listener.Close()
	if err != nil {
		logrus.Errorf("listen address: %s fail, err: %v", address, err)
		fmt.Println("listener=", listener)
		return
	}

	for {
		conn, err := listener.Accept()
		if err != nil {
			logrus.Errorf("accept fail, err: %v", err)
			continue
		}

		go handleClient(conn)
	}
	
}

func handleClient(conn net.Conn) {

	logrus.SetFormatter(&logrus.TextFormatter {
		ForceColors: true,
		FullTimestamp: true,
	})

	defer conn.Close()

	for {
		reader := bufio.NewReader(conn)
		message, err := reader.ReadString('\n')
		if err != nil {
			logrus.Errorf("read message fail, err: %v", err)
			break
		}
		message = strings.TrimSpace(message)
		logrus.Infof("message=%s", message)

	}
}

